/**
 * 入参
 *
 */
import React, { PureComponent } from 'react';
import { NoDataC, PrimaryGhostC, TableC } from '../../../../comps';
import { CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, message, Popover, Popconfirm } from 'antd';
import style from '../index.less';
import SettingColumnsC from './settingColumnsC';
import { connect } from 'dva';

class ResultC extends PureComponent {
  static defaultProps = {};
  state = {
    currentPage: 1,
    numInPage: 10,
    total: 0,
    columns: [],
    dataSource: [],
    sortItem: undefined, // 排序字段
    sortType: undefined, // 排序类型
    sortedInfo: null, //排序对象
    timeStamp: undefined, //时间戳
    bondGroupList: [], //关注按钮---个券组列表
    newBondList: [], //个券组选择列表
    selcetTopAtt: false, //多选顶部关注按钮
    selcetAtt: false, //多选关注按钮
    rowData: {}, //列表关注参数
    groupId: '',
    selectedRows: [], //个券多选择的值
    selectedRowKeys: [],
    isDefault: undefined, //是否是券池过来的个券组
  };
  UNSAFE_componentWillMount() {}
  componentDidMount() {
    this.getAttentionTable().then((res) => {
      // 获取筛选结果表格数据
      this.getResult();
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { settingInfo } = this.props;
    if (settingInfo !== nextProps.settingInfo) {
      this.setState(
        {
          currentPage: 1,
          numInPage: 10,
          total: 0,
        },
        () => {
          this.getResult(nextProps.settingInfo);
        },
      );
    }
  }

  // 获取筛选结果表格数据
  getResult = (settingInfo) => {
    if (this.state.sortedInfo && this.state.sortedInfo.column && this.state.sortedInfo.column.sort == 'false') return; //不排序字段不进行请求
    this.props.dispatch({
      type: 'AssetPreparationM/getResult',
      payload: {
        info: settingInfo || this.props.settingInfo,
        currentPage: this.state.currentPage,
        numInPage: this.state.numInPage,
        sortItem: this.state.sortItem, // 排序字段
        sortType: this.state.sortType, // 排序类型
        columns: settingInfo ? [] : this.state.columns, //用于比对当前展示列 重新点击筛选则columns置空
        type: this.props.type,
      },
      callback: (data) => {
        if (data) {
          this.props.dispatch({
            //手工拼接status 因为表格数据和关注状态不在一个表
            type: 'AssetPreparationM/getStatusList',
            payload: {
              codeList: data.dataSource.map((item) => {
                //证券代码列表
                return {
                  tradingcode: item.tradingcode,
                  exchangecode: item.exchangecode,
                };
              }),
              groupIds: this.state.newBondList && this.state.newBondList.length ? this.state.newBondList.map((item) => item.value) : [], //个券组id
            },
            callback: (statusList) => {
              let arr = [];
              data.dataSource.map((item) => {
                item.selected = false;
                arr.push(item);
                statusList &&
                  statusList.map((x) => {
                    if (item.exchangecode == x.exchangecode && item.tradingcode == x.tradingcode) {
                      item.status = x.status;
                    }
                  });
              });
              let columns = data ? data.columns : [];
              if (columns.length && columns[columns.length - 1].key != 'status') columns.push({ key: 'status', title: '是否关注', selected: true }); //前端加入一列，后端不好操作
              this.setState({
                columns: [...columns],
                timeStamp: new Date().getTime(), //更新时间戳 通知列设置更新树形结构
                dataSource: arr,
                total: data && data.pageInfo ? data.pageInfo.total : 0,
              });
            },
          });
        } else {
          this.setState({
            currentPage: 1,
            numInPage: 10,
            total: 0,
            columns: [],
            dataSource: [],
            sortItem: undefined, // 排序字段
            sortType: undefined, // 排序类型
            sortedInfo: null, //排序对象
            timeStamp: new Date().getTime(), //更新时间戳 通知列设置更新树形结构
          });
        }
      },
    });
  };

  //表格排序change事件
  handleTableChange = (pagination, filt, sorter) => {
    const { current, pageSize } = pagination;
    if (sorter) {
      if (sorter.columnKey == 'selection-column') return; //全选不排序
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      });
      if (sorter.order == 'descend') {
        // 降序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'descend', // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getResult();
          },
        );
      } else if (sorter.order == 'ascend') {
        // 升序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'ascend', // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getResult();
          },
        );
      } else {
        // 无序
        this.setState(
          {
            sortedInfo: sorter,
            sortItem: sorter.field, // 排序字段
            sortType: undefined, // 排序类型
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getResult();
          },
        );
      }
    }
  };

  changeColumns = (columns) => {
    this.setState({
      columns: [...columns],
    });
  };

  //获取关注列表
  getAttentionTable = () => {
    const { dispatch } = this.props;
    let p = new Promise((resolve) => {
      //获取个券组列表
      dispatch({
        type: 'myAttentionM/getBondGroupList',
        payload: { type: this.props.type == 'ashare' ? 'stock' : 'bond' }, //股票和债券 不同的入参
        callback: (res) => {
          res.data.map((item) => {
            item.isAttention = false;
          });
          this.setState({
            bondGroupList: res.data,
            newBondList: res.data,
          });
          resolve(res.data);
        },
      });
    });
    return p;
  };

  //点击关注按钮事件
  attentionBtn = () => {
    const { bondGroupList, selcetTopAtt } = this.state;
    if (bondGroupList.length == 0) {
      //无关注组时
      message.warning('请先添加个券的关注分组');
    } else {
      this.setState({
        rowData: {},
        groupId: '',
        isDefault: undefined,
        selcetAtt: false,
        selcetTopAtt: !selcetTopAtt,
        newBondList: [...this.state.bondGroupList],
      });
    }
  };

  //关注列表点击事件
  listClick = (data) => {
    const value = data.value;
    const list = JSON.parse(JSON.stringify(this.state.newBondList));
    list.map((item) => {
      if (item.value == value) {
        item.isAttention = !item.isAttention;
      } else {
        item.isAttention = false;
      }
    });
    this.setState({
      groupId: data.isAttention ? '' : value,
      isDefault: data.isDefault, //是否是券池过来的数据
      newBondList: list,
    });
  };

  //取消btn
  cancelClick = () => {
    this.setState({
      rowData: {},
      selcetTopAtt: false,
      selcetAtt: false,
      groupId: '',
      isDefault: undefined,
    });
    this.setState({
      newBondList: [...this.state.bondGroupList],
    });
  };

  //确定btn
  sureClick = () => {
    const { groupId, selectedRows, rowData, selcetTopAtt } = this.state;
    if (!groupId) {
      message.warning('请选择个券组');
      return;
    }
    let list = [];
    if (selcetTopAtt) {
      list = selectedRows;
    } else {
      list.push(rowData);
    }
    let selectList = [];
    list.map((item) => {
      let obj = {
        groupId: groupId,
        tradingCode: item.tradingcode,
        exchangeCode: item.exchangecode,
        tradingName: item.secuabbr,
      };
      selectList.push(obj);
    });

    this.props.dispatch({
      type: 'myAttentionM/addBondAttention',
      payload: {
        selectList: selectList,
        isDefault: this.state.isDefault,
      },
      callback: (res) => {
        message.success('关注成功');
        this.setState(
          {
            rowData: {},
            selcetTopAtt: false,
            selcetAtt: false,
            selectedRows: [],
            selectedRowKeys: [],
            groupId: '',
            isDefault: undefined,
            newBondList: [...this.state.bondGroupList],
          },
          () => {
            this.getResult(); //重新查询结果列表
          },
        );
      },
    });
  };

  //关注下拉列表
  showPopover = () => {
    const { selcetTopAtt, selectedRows } = this.state;
    return (
      <Popover
        overlayClassName={style.popoverBox}
        placement='bottomRight'
        visible={selcetTopAtt}
        content={this.listNode()}
        trigger='click'
        onVisibleChange={() => this.attentionBtn()}
      >
        <PrimaryGhostC title='关注' style={{ margin: '10px' }} disabled={selectedRows.length == 0 ? true : false} />
      </Popover>
    );
  };

  //关注下拉列表
  listNode = () => {
    const { newBondList } = this.state;
    return (
      <div className='confirm-box'>
        <div className='confirm-list'>
          <ul>
            <li>
              <a>
                <div className='list-item'>
                  <span>请选择加入的个券组</span>
                </div>
              </a>
            </li>
            {newBondList.map((item) => (
              <li key={item.value}>
                <a className={item.isAttention ? 'a-active' : ''} onClick={(e) => this.listClick(item)}>
                  <div className='list-item'>
                    <span>{item.title}</span>
                    <CheckOutlined className='list-icon' />
                  </div>
                </a>
              </li>
            ))}
          </ul>
        </div>
        <div className='confirm-btn'>
          <Button onClick={(e) => this.cancelClick()}>取消</Button>
          <Button type='primary' onClick={(e) => this.sureClick()}>
            确定
          </Button>
        </div>
      </div>
    );
  };
  //取消关注
  cancelFocus = (data) => {
    this.props.dispatch({
      type: 'AssetPreparationM/cancelFocus',
      payload: {
        //个券组下拉列表
        groupIds: this.state.newBondList && this.state.newBondList.length ? this.state.newBondList.map((item) => item.value) : [],
        tradingCode: data.tradingcode,
        exchangeCode: data.exchangecode,
      },
      callback: (data) => {
        if (data) {
          message.success('取消关注成功!');
          this.getResult(); //刷新列表
        }
      },
    });
  };

  render() {
    const { settingInfo } = this.props;
    const { currentPage, total, numInPage, columns, dataSource, selectedRowKeys } = this.state;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo ? sortedInfo : {};
    let newColumns = columns ? columns.filter((item) => item.selected == true) : [];
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        if (selectedRowKeys && selectedRowKeys.length > 0) {
          this.setState({
            selectedRowKeys: selectedRowKeys,
            selectedRows: selectedRows,
          });
        } else {
          this.setState({
            selectedRowKeys: [],
            selectedRows: [],
          });
        }
      },
    };
    newColumns &&
      newColumns.map((item, key, arr) => {
        if (item.sort === 'true') {
          item.sorter = true;
          if (item.key != 'tradingcode_suffix') {
            item.align = 'right';
          }
          item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
        }
        if (item.key == 'secuabbr' || item.key == 'tradingcode_suffix') {
          item.fixed = arr.length > 6 ? 'left' : undefined; //当列过少 会出现重复列
          item.width = arr.length > 6 ? '100px' : undefined;
        }
        if (item.key == 'status') {
          item.fixed = arr.length > 6 ? 'right' : undefined; //当列过少 会出现重复列
          item.width = arr.length > 6 ? '100px' : undefined;
          item.render = (text, record) => {
            return (
              <Popconfirm
                title={'若取消关注，该资产会从所有个券组中移除，是否取消？'}
                icon={<ExclamationCircleOutlined />}
                onConfirm={() => this.cancelFocus(record)}
                disabled={text == '1' ? false : true}
                overlayStyle={{ width: '210px' }}
              >
                <a disabled={text == '1' ? false : true}>{text == '1' ? '已关注' : '未关注'}</a>
              </Popconfirm>
            );
          };
        }
      });

    return (
      <div>
        {settingInfo ? (
          <div>
            <div style={{ textAlign: 'right' }}>
              <SettingColumnsC data={columns} changeColumns={this.changeColumns} timeStamp={this.state.timeStamp} />
              {this.showPopover()}
            </div>
            {JSON.stringify(dataSource) === '[]' ? (
              <NoDataC />
            ) : (
              <TableC
                columns={newColumns}
                loading={this.props.loading == true}
                rowSelection={rowSelection}
                dataSource={dataSource}
                current={currentPage}
                total={total}
                pageSize={numInPage}
                rowKey='index'
                scroll={{ x: 'max-content' }}
                onChange={this.handleTableChange}
              />
            )}
          </div>
        ) : (
          <div
            style={{
              height: '300px',
              textAlign: 'center',
              paddingTop: '100px',
            }}
          >
            请先选中筛选条件,加载相应数据!
          </div>
        )}
      </div>
    );
  }
}
export default connect(({ AssetPreparationM, userM: user, loading, myAttentionM }) => ({
  AssetPreparationM,
  user,
  loading: loading.effects['AssetPreparationM/getResult'],
  myAttentionM,
  currentUser: user.currentUser,
}))(ResultC);
